﻿using AutoMapper;
using DFGK.IRepository;
using DFGK.IRepository.LY;
using DFGK.IService.LY;
using DFGK_WMS.Model.Models.LyModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DFGK.Service.LY
{
    public class PurchasePlanService : BaseService, IPurchasePlanService
    {
        private readonly IPurchasePlanRepository _purchasePlanRepository;
        private readonly IUnitOfWork _unitOfWork;
        public PurchasePlanService(IMapper mapper, IPurchasePlanRepository purchasePlanRepository, IUnitOfWork unitOfWork) : base(mapper)
        {
            _purchasePlanRepository = purchasePlanRepository;
            _unitOfWork = unitOfWork;
        }

        public bool AddOrModefiyPurchasePlan(PurchasePlan model, out string errorMsg)
        {
            errorMsg = string.Empty;
            if (model.Id > 0)
            {
                _purchasePlanRepository.UpdEntity(model);
            }
            else
            {
                _purchasePlanRepository.AddEntity(model);

            }
            return _unitOfWork.SaveChangesEntity();
        }

        public bool DelPurchasePlan(long purchasePlanId)
        {
            var Quote = _purchasePlanRepository.QueryEntityById(purchasePlanId);
            if (Quote == null)
            {
                return false;
            }
            _purchasePlanRepository.DelEntity(Quote);
            return _unitOfWork.SaveChangesEntity();
        }

        public PurchasePlan? GetPurchasePlan(long purchasePlanId)
        {
            return _purchasePlanRepository.QueryEntityById(purchasePlanId);
        }

        public List<PurchasePlan> GetPurchasePlanData(string? name, DateTime? startDate, DateTime? endDate , string? status,out int totalCount, int pageIndex = 1, int pageSize = 15)
        {
            var list = _purchasePlanRepository.GetEntityAlls();
            if (!string.IsNullOrEmpty(name))
            {
                list = list.Where(d => d.PlanName.Contains(name));
            }
            if (!string.IsNullOrEmpty(status))
            {
                list = list.Where(d => d.Status==status);
            }
            if (startDate!=null)
            {
                list = list.Where(d => d.StartDate >=startDate);
            }
            if (endDate!=null)
            {
                list = list.Where(d => d.EndDate <=endDate);
            }
            totalCount = list.Count();
            list = list.Skip((pageIndex - 1) * pageSize).Take(pageSize).OrderByDescending(d => d.Id);
            return list.ToList();
        }
    }
}
